<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\common\model\dealer;

use cores\BaseModel;
use think\model\relation\BelongsTo;

/**
 * 分销商推荐关系模型
 * Class Referee
 * @package app\common\model\dealer
 */
class Referee extends BaseModel
{
    // 定义表名
    protected $name = 'dealer_referee';

    // 定义主键
    protected $pk = 'id';

    /**
     * 关联用户表
     * @return BelongsTo
     */
    public function user(): BelongsTo
    {
        $module = self::getCalledModule();
        return $this->belongsTo("app\\{$module}\\model\\User");
    }

    /**
     * 关联分销商用户表
     * @return BelongsTo
     */
    public function dealer(): BelongsTo
    {
        $module = self::getCalledModule();
        return $this->belongsTo("app\\{$module}\\model\\User", 'dealer_id')
            ->where('is_delete', '=', 0);
    }

    /**
     * 获取上级用户id
     * @param int $userId
     * @param int $level
     * @param bool $isDealer 必须是分销商
     * @return bool|mixed
     */
    public static function getRefereeUserId(int $userId, int $level, bool $isDealer = false)
    {
        $dealerId = (new self)->where(['user_id' => $userId, 'level' => $level])->value('dealer_id');
        if (!$dealerId) return 0;
        return $isDealer ? (User::isDealerUser($dealerId) ? $dealerId : 0) : $dealerId;
    }

    /**
     * 获取我的团队列表
     * @param int $dealerId 分销商ID
     * @param array $param
     * @return \think\Paginator
     */
    public function getList(int $dealerId, array $param = []): \think\Paginator
    {
        // 默认查询参数
        $params = $this->setQueryDefaultValue($param, [
            'level' => -1,  // 推荐关系
            'search' => '',     // 搜索内容
        ]);
        // 检索查询条件
        $filter = [];
        $params['level'] > -1 && $filter[] = ['level', '=', (int)$params['level']];
        !empty($params['search']) && $filter[] = ['user.nick_name|user.mobile', 'like', "%{$params['search']}%"];
        // 返回列表数据
        return $this->with(['user.avatar'])
            ->alias('referee')
            ->field('referee.*')
            ->join('user', 'user.user_id = referee.user_id')
            ->where($filter)
            ->where('referee.dealer_id', '=', $dealerId)
            ->where('user.is_delete', '=', 0)
            ->order(['referee.create_time' => 'desc'])
            ->paginate(15);
    }
}